package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;

import com.tbvtc.agriculturalcreditchainserver2025.service.AiService;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestHttpUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestReportUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PesticideReportGenerator;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@RestController
@RequestMapping("/ai")
@Tag(name = "AI接口")
@CrossOrigin
public class AiController {

    @Autowired
    private AiService aiService;
    @Resource
    private PestHttpUtils pestHttpUtils;

    /**
     * AI对话接口
     * @param prompt
     * @param chatId
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    @Operation(summary = "AI")
    public Flux<String> chat(String prompt, String chatId, String userId) {
        WebClient client = WebClient.create("http://localhost:8080");
        Flux<String> responseFlux = client.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/ai/chat")
                        .queryParam("prompt", prompt)
                        .queryParam("chatId", chatId)
                        .queryParam("userId", userId)
                        .build())
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class);
        // 用于标记是否是第一条数据
        AtomicBoolean isFirst = new AtomicBoolean(true);
        // 处理Flux，在第一条数据前添加前缀
        return responseFlux.transform(flux -> flux.map(content -> {
            if (isFirst.getAndSet(false)) { // 第一次进入时为true，之后变为false
                return "<think>aaa</think>" + content;
            } else {
                return content;
            }
        }));

    }

    /**
     * 根据用户名获取所有历史会话id
     * @param userId
     * @return
     */

    @GetMapping("/history")
    @Operation(summary = "根据用户名获取所有历史会话id")
    public Result getHistory(String userId) {
        WebClient webClient = WebClient.create("http://localhost:8080");

        return RUtils.success(webClient.get()
                .uri("/ai/history/{userId}", userId)
                .retrieve()
                .toEntity(List.class)
                .blockOptional()
                .map(HttpEntity::getBody)
                .orElse(null));
    }

    /**
     * 根据用户名和会话id查询对话历史记录
     * @param userId
     * @param chatId
     * @return
     */
    @GetMapping("/history/{userId}/{chatId}")
    @Operation(summary = "根据用户名和会话id查询对话历史记录")
    public Result getHistory(@PathVariable String userId, @PathVariable String chatId) {
        WebClient webClient = WebClient.create("http://localhost:8080");
        return RUtils.success(
                webClient.get()
                .uri("/ai/history/{userId}/{chatId}", userId, chatId)
                .retrieve() // 发送GET请求
                .toEntity(List.class) // 解析响应为List<String>
                .blockOptional() // 获取Optional<HttpEntity<List<String>>>
                .map(HttpEntity::getBody)// 获取List<String>
                .orElse(null));// 返回结果
    }

    /**
     * 根据用户名和会话id删除对话历史记录
     * @param userId
     * @param chatId
     * @return
     */
    @Operation(summary = "根据用户名和会话id删除对话历史记录")
    @DeleteMapping("/history/{userId}/{chatId}")
    public Result removeHistory(@PathVariable("userId") Integer userId, @PathVariable("chatId") String chatId ) {
        WebClient webClient = WebClient.create("http://localhost:8080");

// 发送 DELETE 请求（带响应处理）
        webClient.delete()
                .uri("/ai/history/{userId}/{chatId}", userId, chatId)
                .retrieve()
                .toBodilessEntity()  // 明确表示不期待响应体
                .block();            // 阻塞等待请求完成（如果是异步环境可省略）
        return RUtils.success();
    }
    @Operation(summary = "获取智能体建议方法")
    @GetMapping("/getSuggestion")
    public Result getSuggestion( @RequestParam("temperatureDifference") String temperatureDifference,
                                 @RequestParam("illumination") String illumination,
                                 @RequestParam("temperature") String temperature,
                                 @RequestParam("humidity") String humidity) {
        String prompt="现在梨温度"+temperature+"，湿度"+humidity+"，光照"+illumination+"，" +
                "温差"+temperatureDifference+"，该环境下的梨好吃吗，给个分数";
//        String treatmentMethod = pestHttpUtils.getTreatmentMethodByAi("1", "1", "1", 1L, "1");
        return RUtils.success(null);
    }
}
